<template>
  <div id="app">
    <!-- 登录页面：独立布局 -->
    <div v-if="isLoginPage" class="min-h-screen">
      <router-view />
    </div>

    <!-- 系统主界面：包含导航栏和页脚 -->
    <div v-else class="min-h-screen bg-gray-50 flex flex-col">
      <!-- 渐变蓝导航栏（严格闭合） -->
      <header class="bg-gradient-to-r from-sky-500 to-indigo-600 text-white shadow-lg">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
          <!-- 标题区域 -->
          <h1 class="text-2xl font-bold flex items-center">
            <font-awesome-icon icon="file-contract" class="mr-2" />
            电子合同标准化云平台系统
          </h1>

          <!-- 导航项区域（严格闭合） -->
          <nav class="flex items-center space-x-6">
            <ul class="flex space-x-6">
              <li
                  v-for="item in navigationItems"
                  :key="item.name"
                  @click="navigateTo(item.path)"
                  :class="getNavItemClass(item.name)"
              >
                <font-awesome-icon :icon="item.icon" class="mr-1" />{{ item.label }}
              </li>
            </ul>

            <!-- 用户信息区（父容器：relative 定位） -->
            <div class="flex items-center space-x-4 ml-8 pl-4 border-l border-white/20 relative">
              <!-- 用户交互触发区 -->
              <div
                  class="flex items-center space-x-2 text-sm cursor-pointer group"
                  @click="showUserInfo = !showUserInfo"
                  @mouseenter="showUserInfo = true; handleMouseOver()"
                  @mouseleave="handleMouseLeave()"
              >
                <font-awesome-icon icon="user-circle" class="text-lg transition-transform group-hover:scale-110" />
                <span class="group-hover:underline">{{ currentUser.name || currentUser.username }}</span>
                <font-awesome-icon
                    icon="chevron-down"
                    class="text-xs transition-transform"
                    :class="showUserInfo ? 'rotate-180' : ''"
                />
              </div>

              <!-- 悬浮窗：完全贴导航栏底部，无遮挡 -->
              <div
                  v-if="showUserInfo"
                  class="absolute
         top-[calc(100%+12px)]  <!-- 父容器底部+12px，彻底分离 -->
         right-0
         w-64
         bg-white
         rounded-lg
         shadow-xl
         p-4
         text-gray-800
         z-50
         border border-gray-100
         transition-all
         duration-300"
                  @mouseenter="showUserInfo = true; handleMouseOver()"
                  @mouseleave="handleMouseLeave()"
              >
                <!-- 用户基础信息 -->
                <div class="flex items-center mb-3 pb-3 border-b border-gray-100">
                  <div class="w-10 h-10 rounded-full bg-gradient-to-br from-sky-500 to-indigo-600 flex items-center justify-center text-white mr-3">
                    <font-awesome-icon icon="user" />
                  </div>
                  <div>
                    <div class="font-medium">{{ currentUser.name || currentUser.username }}</div>
                    <div class="text-xs text-gray-500">{{ currentUser.company || '未设置公司信息' }}</div>
                  </div>
                </div>

                <!-- 详细信息列表 -->
                <div class="space-y-3 text-sm">
                  <div class="flex justify-between">
                    <span class="text-gray-500">手机号</span>
                    <span>{{ currentUser.phone || '未设置' }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-500">邮箱</span>
                    <span>{{ currentUser.email || '未设置' }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-500">所属行业</span>
                    <span>{{ formatIndustry(currentUser.industry) || '未设置' }}</span>
                  </div>
                </div>
              </div>

              <!-- 登出按钮 -->
              <button
                  @click="handleLogout"
                  class="flex items-center space-x-1 px-3 py-1 rounded-md bg-white/10 hover:bg-white/20 transition-all text-sm">
                <font-awesome-icon icon="sign-out-alt" />
                <span>登出</span>
              </button>
            </div>
          </nav>
        </div>
      </header>

      <!-- 主内容区 -->
      <main class="flex-grow container mx-auto px-4 py-6">
        <router-view />
      </main>

      <!-- 页脚（严格闭合） -->
      <footer class="bg-gray-800 text-white py-4">
        <div class="container mx-auto px-4 text-center text-sm">
          <p>© 2023 合同管理系统 版权所有</p>
        </div>
      </footer>
    </div>
  </div>
</template>

<script>
import { logoutApi } from '@/api/user'

export default {
  name: 'App',
  data() {
    return {
      showUserInfo: false,  // 悬浮窗显隐控制
      hideTimer: null,       // 延迟隐藏计时器
      currentUser: { username: '用户', name: '用户' } // 初始化默认值
    }
  },
  computed: {
    isLoginPage() {
      return this.$route && this.$route.name === 'Login';
    },
    currentRouteName() {
      return this.$route ? this.$route.name : null;
    },
    navigationItems() {
      const items = [
        { path: '/', name: 'ContractTemplates', icon: 'file-alt', label: '合同模板' },
        { path: '/business-messages', name: 'BusinessMessages', icon: 'briefcase', label: '业务消息' },
        { path: '/system-messages', name: 'SystemMessages', icon: 'bell', label: '系统消息' },
        { path: '/profile', name: 'Profile', icon: 'user', label: '个人信息' },
        { path: '/orders', name: 'Orders', icon: 'list-alt', label: '服务订单' },
        { path: '/favorites', name: 'Favorites', icon: 'star', label: '我的收藏' }
      ];
      
      // 如果当前用户是管理员，添加管理员页面链接
      // 修复角色判断逻辑，数据库中角色为"ADMIN"而不是"admin"
      if (this.currentUser && this.currentUser.role === 'ADMIN') {
        items.push({ path: '/admin', name: 'Admin', icon: 'user-shield', label: '管理员面板' });
      }
      
      return items;
    }
  },
  mounted() {
    // 页面加载时获取用户信息
    this.loadUserInfo();
    
    // 监听用户登录事件
    window.addEventListener('user-login', this.loadUserInfo);
  },
  beforeUnmount() {
    // 清理事件监听器
    window.removeEventListener('user-login', this.loadUserInfo);
    this.hideTimer && window.clearTimeout(this.hideTimer);
  },
  methods: {
    loadUserInfo() {
      const userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        try {
          this.currentUser = JSON.parse(userInfo);
        } catch (e) {
          console.error('解析用户信息失败:', e);
          this.currentUser = { username: '用户', name: '用户' };
        }
      } else {
        this.currentUser = { username: '用户', name: '用户' };
      }
    },
    getNavItemClass(routeName) {
      return this.currentRouteName === routeName
          ? 'text-black-300 font-medium'
          : 'hover:text-blue-100 transition py-1';
    },
    navigateTo(path) {
      this.$router && this.$router.push(path);
    },
    handleLogout() {
      if (confirm('确定要退出系统吗？')) {
        // 调用后端登出接口
        logoutApi().finally(() => {
          // 无论后端是否成功，都清除本地数据
          localStorage.removeItem('token');
          localStorage.removeItem('userInfo');
          this.currentUser = { username: '用户', name: '用户' }; // 重置用户信息
          this.$router.push('/login');
        });
      }
    },
    formatIndustry(industryCode) {
      const industryMap = {
        'IT': '信息技术', 'finance': '金融', 'education': '教育',
        'medical': '医疗健康', 'other': '其他行业'
      };
      return industryMap[industryCode] || industryCode;
    },
    handleMouseLeave() {
      this.hideTimer = window.setTimeout(() => this.showUserInfo = false, 300);
    },
    handleMouseOver() {
      this.hideTimer && window.clearTimeout(this.hideTimer);
    }
  },
  watch: {
    // 监听路由变化，确保用户信息是最新的
    '$route'() {
      this.loadUserInfo();
    }
  }
}
</script>

<style>
body {
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}
header nav li {
  cursor: pointer;
}
</style>